package com.byron.media.server.test;

import com.byron.media.server.MediaServer;
import com.byron.media.server.client.MediaClient;
import com.byron.media.server.config.MediaServerConfig;
import com.byron.media.server.handlers.SessionContainer;
import com.byron.media.server.model.DataFactory;
import com.byron.media.server.model.MediaData;
import com.byron.media.server.utils.CommonUlit;
import com.byron.media.server.utils.FrameInfo;
import com.byron.media.server.utils.MediaClientConfig;
import com.byron.media.server.utils.MediaType;

public class MediaTestSender implements Runnable{
    
    private int speed;          // 每秒发送的KB数量

    private String groupName;       // 发送的组名

    private MediaClient mediaClient;

    private MediaServerConfig config;

    private boolean running;        // 线程控制

    private long seq = 1;

    private byte channel;

    private long ID;

    private DataFactory dataFactory;

    private SessionContainer sessionContainer;

    public MediaTestSender(String server, int port, String group, byte channel, long ID, int speed){
        this.speed = speed;

        // TODO 未完成
//        this.config = new MediaServerConfig();
//        this.config.setMainServer(server);
//        this.config.setMainServerPort(port);
//        this.config.setServerPort(port);
//        this.config.setServerAddress(server);
//        this.config.setGroup(group);
//        this.config.setDevice(ID + "");
        this.channel = channel;
        this.ID = ID;

        this.seq = 1;
    }

//    @Override
    public void start() {
        mediaClient = new MediaClient(dataFactory, sessionContainer, config);
        mediaClient.start();

        running = true;
        // 开启定时器，定时向队列推送固定长度的byte数据
        new Thread(this).start();
    }

//    @Override
//    public void pushFrameInfo(FrameInfo frameInfo) {
//
//    }

//    @Override
    public void close() {
        mediaClient.close();
        mediaClient = null;
        running = false;
    }

    @Override
    public void run() {

        long millis = 1000 / speed;
        int nanos = 1000 % speed * 100;

        while(running){
            MediaData mediaData = dataFactory.createData(MediaServer.MTU);
            mediaData.setChannel((byte) 0);
            mediaData.setSeq(seq);
            byte type = 0;
            type = MediaType.putTest(type);
            type = MediaType.putStart(type);
            type = MediaType.putEnd(type);
            mediaData.setType(type);
            CommonUlit.putLong(mediaData.getData(), seq, 0);
            seq ++;
            mediaClient.send(mediaData);
            try {
                Thread.sleep(millis, nanos);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
}
